const invalidPrinter = ["Fax", "Send To Microsoft OneNote", "Microsoft Office Document Image Writer"];

var socket = null;
var PrintHelp = {
    /***
     *
     * 获取请求的UUID，指定长度和进制,如
     * getUUID(8, 2)   //"01001010" 8 character (base=2)
     * getUUID(8, 10) // "47473046" 8 character ID (base=10)
     * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
     *
     */
    getUUID: function (len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    },
    list: {},
    init: function (callback) {
        this.doConnect();
        callback();
        window.onbeforeunload = function () {
            console.log('onbeforeunload close webSocket');
            socket && socket.close();
        }
    },
    /**
     * 连接打印客户端
     */
    doConnect: function (success, error) {
        var list = this.list;
        if (socket !== null) {
            success && success();
        } else {
            try {
                var protocol = window.location.protocol;
                var wsUrl = "";
                //如果需要在mac环境下测试，可以使用nginx配置反向代理；
                //不建议修改此地址，容易遗忘情况下发布上去。
                if (protocol == "http:") {
                    wsUrl = "ws://localhost:13528";
                } else {
                    wsUrl = "wss://localhost:13529";
                }
                socket = new WebSocket(wsUrl);
                // 打开Socket
                socket.onopen = function (event) {
                    success && success();
                    // 监听消息
                    socket.onmessage = function (event) {
                        var data = JSON.parse(event.data);
                        list[data.cmd] && list[data.cmd](data);
                    };
                    // 监听Socket的关闭
                    socket.onclose = function (event) {
                        socket = null;
                        console.log('与云打印组件的连接已经被关闭。', event);
                    };
                };
                socket.onerror = function (event) {
                    error && error();
                    socket = null;
                };
            } catch (e) {
                console.log(e);
                error && error();
            }
        }
    },
    clearSocket: function () {
        socket = null;
    },
    /***
     * 构造request对象
     */
    getRequestObject: function (cmd) {
        return {
            requestID: this.getUUID(8, 16),
            version: "1.0",
            cmd: cmd
        }
    },
    getCMD: function (cmd, ext, fn) {
        this.list[cmd] = fn; //临时保存的，在socket返回时调用 //这种单例存在并发覆盖的问题；
        var request = this.getRequestObject(cmd);
        /*
         ext  格式
         {
         task: {}
         }
         */
        Object.assign(request, ext);
        this.send(JSON.stringify(request));
    },
    /**
     * 发送数据
     * @param request
     * @param callback
     */
    send: function (request, callback) {
        var self = this;
        if (socket && request) {
            if (socket.readyState === 1) {
                socket.send(request);
                callback && callback();
            } else {
                setTimeout(function () {
                    self.send(request, callback);
                }, 500);
            }
        } else {
            if (!socket) {
                self.doConnect(function () {
                    self.send(request, callback);
                }, function () {
                    console.log("与打印组件建立连接失败，请检查打印组件是否正在运行。");
                });
            }
        }
    },
    /**
     * 获取打印机列表
     * @param callback
     */
    getPrinters: function (callback) {
        this.getCMD("getPrinters", {}, function (data) {
            callback && callback(data);
        });
    },
    /**
     * 获取打印机列表，并过滤一些普通用户不需要的虚拟打印机
     * @param {*} callback 
     */
    getPrinterList(callback) {
        let self = this;
        this.getPrinters(function (data) {
            let printers = data.printers || [];
            let formatPrinteList = [];
            printers.forEach(printer => {
                if (self.filterName(printer.name) !== null) {
                    formatPrinteList.push(printer.name);
                }
            });
            callback && callback(formatPrinteList);
        });
    },
    /**
     * 过滤一些无效的打印机
     * @param {*} name 
     */
    filterName(name) {
        let lowName = name.toLowerCase();
        for (var i = 0; i < invalidPrinter.length; i++) {
            if (lowName === invalidPrinter[i].toLocaleLowerCase()) {
                return null;
            }
        }
        return lowName;
    },
    /**
     * 获取客户端版本信息
     */
    getAgentInfo: function (callback) {
        this.getCMD("getAgentInfo", {}, function (data) {
            callback && callback(data);
        });
    },
    getCainiaoVersion(callback){
        this.getAgentInfo(function (data) {
            callback && callback(data.version || '0.0.0.0');
        });
    },
};

export default PrintHelp;
